import React, { PureComponent } from 'react';
import { Table, notification, Button, Select, Icon } from 'antd';
import { connect } from 'dva';
import StructureBase from "../../components/forms/structureBase"
import "./index.less"
import "../../Common.less"
import ToolConfigModals from '../../components/toolConfigModals';
import { worker } from "../../utils/worker"
import {cloneDeep} from "lodash"
const { Option } = Select;
class structureDetail extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            cindex1: null,
            cindex2: null,
            otype: null,
            mode: "",
            showBg:false,
            tloading: false,
            loading: true,

        }
        this.editProp = this.editProp.bind(this)
        this.getFormData = this.getFormData.bind(this)
        this.modalConfirm = this.modalConfirm.bind(this)
        this.submit = this.submit.bind(this)
        this.getData = this.getData.bind(this)

    }

    async modalConfirm(data, type) {
        const { otype, cindex1, cindex2, attributeProperties, customProperties, treeData } = this.state;
        if (type == 1) {
            if (otype == 1) {
                Object.assign(attributeProperties[cindex1], data)
                attributeProperties.splice(cindex1, 1, attributeProperties[cindex1])
            } else {
                Object.assign(customProperties[cindex2], data)
                customProperties.splice(cindex2, 1, customProperties[cindex2])
            }
        } else {
            if (otype == 1) {
                Object.assign(attributeProperties[cindex1], data)
                attributeProperties.splice(cindex1, 1, attributeProperties[cindex1])
            } else {
                Object.assign(customProperties[cindex2], data)
                customProperties.splice(cindex2, 1, customProperties[cindex2])
            }
        }
        const len = customProperties.length;
        const len2 = attributeProperties.length
        for (let i = 0; i < len; i++) {
            let item = customProperties[i];
            const obj = item.definitionPartId ? await worker.getTreeNode(treeData, item.definitionPartId) : ""
            item.definitionPartName = obj ? obj.title : ""
        }
        for (let i = 0; i < len2; i++) {
            const item = customProperties[i];
            const obj = item.definitionPartId ? await worker.getTreeNode(treeData, item.definitionPartId) : ""
            console.log(obj)
            item.definitionPartName = obj ? obj.title : ""
        }
        this.setState({
            attributeProperties: [...attributeProperties], customProperties: [...customProperties]
        })

    }
    async editProp(e, item, type) {
        e.preventDefault()

        let { attributeProperties, customProperties } = this.state;
        let values = await this.state.context.getFormValues(true)
        if (!values.definitionPartIds || !values.definitionPartIds.length) {
            notification.warn({ message: "请选择部位" })
            return;
        }
        if (type == 1) {
            let index = attributeProperties.findIndex(item2 => item2.key == item.key);
            this.setState({
                otype: 1,
                cindex1: index
            })
        } else {
            let index = customProperties.findIndex(item2 => item2.key == item.key);
            this.setState({
                otype: 2,
                cindex2: index
            })
        }
        this.state.modalContext.updateModal({
            visible: true,
            title: "修改属性",
            event: { code: 'propsEdit' },
            extra: {
                mode: "edit",
                propData: item,
                checkedKeys: values.definitionPartIds,
                colNum: values.colNum
            }
        });
    }
    getFormData(data) {
        if (data) {
            this.setState({
                attributeProperties: data.attributeProperties, customProperties: data.customProperties, definitionFiles: data.definitionFiles, dirName: data.dirName
            })
        }

    }
    async componentDidMount() {
        const { dictlist } = this.props

        let a = this.props.match.params
        let res = await this.props.getStructureTree()
        
        let resc = cloneDeep(await worker.loopTreeNode2(res))
        if (resc) {
            this.setState({
                expandedKeys: resc.map(item => item.key),
                treeData: resc
            })
        }
        let id = a.id;

        let res2 = await this.props.cusPropsList()
        await this.setState({
            mode: a.mode,
            showBg:a.mode=="overview"?true:false,
            propsList: res2,
            isShowList: dictlist.filter(item => item.dictType == "is_show"),
            isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
            isRequiredList: dictlist.filter(item => item.dictType == "is_required"),
            propertyTypeList: dictlist.filter(item => item.dictType == "property_type"),
            unitList: dictlist.filter(item => item.dictType == "unit"),
            isCalculateList: dictlist.filter(item => item.dictType == "is_calculate"),

        })

        if (a.mode != "add") {
            await this.getData(id)
        }
        let context = this.state.context;
        context.updateFormData({ definitionTreeId: a.definitionTreeId && a.definitionTreeId != '-1' ? a.definitionTreeId : "" })
        this.setState({
            loading: false
        })
    }

    async getData(id) {
        this.setState({
            tloading: true
        })
        const { treeData,mode} = this.state;
        let res = await this.props.getDefinitionPropertyByDefinitionId({ id })
        const { customProperties, attributeProperties, definitionFiles, dirName } = res;
        const len = attributeProperties.length;
        const len2 = customProperties.length
        const len3 = definitionFiles.length
        for (let i = 0; i < len; i++) {
            let item = attributeProperties[i];
            const obj = item.definitionPartId ? await worker.getTreeNode(treeData, item.definitionPartId) : ""
            item.definitionPartName = obj ? obj.title : ""

        }
        for (let i = 0; i < len2; i++) {
            const item = customProperties[i];
            const obj = item.definitionPartId ? await worker.getTreeNode(treeData, item.definitionPartId) : ""
            item.definitionPartName = obj ? obj.title : ""
        }
        for (let i = 0; i < len3; i++) {
            let item = definitionFiles[i];
            item.uid = item.id;
            item.name = item.fileName;
            item.status = 'done';
            item.url = '';
        }
        res.definitionPartIds = res.definitionPartIds.split(',')
      
       
        let context = this.state.context;
        context.updateFormData(res)
        
        this.setState({
            attributeProperties,
            customProperties,
            definitionFiles,
            dirName,
            tloading: false
        })
    }
    async submit(e) {
        const { mode } = this.state;
        e.preventDefault();
        this.setState({
            loading: true
        })
        const { attributeProperties, customProperties, definitionFiles, dirName } = this.state;
        const len = attributeProperties ? attributeProperties.length : 0
        const len2 = customProperties ? customProperties.length : 0
        let finish = true;
        let propIncludes = true;
        
        let values = await this.state.context.getFormValues(true)
        
        if (len) {
            for (let i = 0; i < len; i++) {
                let item = attributeProperties[i];
                if (!item.definitionPartId) {
                    finish = false
                } else {
                    if (values.definitionPartIds && !values.definitionPartIds.includes(String(item.definitionPartId))) {
                        propIncludes = false
                    }
                }

            }
        }
        if (len2) {
            for (let i = 0; i < len2; i++) {
                let item = customProperties[i];
                if (!item.definitionPartId) {
                    finish = false
                } else {
                    if (values.definitionPartIds && !values.definitionPartIds.includes(String(item.definitionPartId))) {
                        propIncludes = false
                    }
                }
            }
        }
        
        if (!finish) {
            notification.warn({ message: "请将所有属性填写完整!" })
            this.setState({
                loading: false
            })
            return;
        }
        if (!propIncludes) {
            notification.warn({ message: "请检查属性所属部位是否正确" })
            this.setState({
                loading: false
            })
            return;
        }
        let context = this.state.context;
        
        context.getFormValues().then(res => {
            res.attributeProperties = attributeProperties;
            res.customProperties = customProperties;
            res.definitionFiles = definitionFiles.map(item => {
                delete item.status;
                return item;
            });
            res.dirName = dirName;
            res.definitionPartIds = res.definitionPartIds.join(',')
            if (mode == 'add') {
                this.props.addDefinition(res, results => {
                    this.setState({
                        loading: false
                    })
                    this.props.history.go(-1)
                }, err => {
                    this.setState({
                        loading: false
                    })
                })
            } else {
                this.props.updateDefinition(res, results => {
                    this.setState({
                        loading: false
                    })
                    this.props.history.go(-1)
                }, err => {
                    this.setState({
                        loading: false
                    })
                })
            }

        }).catch(err => {
            this.setState({
                loading: false
            })
        })
    }
    render() {

        const { loading,showBg, tloading, mode, customProperties, attributeProperties, isShowList, isEffectiveList, propertyTypeList, unitList, propsList } = this.state;
        const c1 = [{
            title: 'KEY',
            dataIndex: 'key',
            key: 'key',
            width: "100px",
        },
        {
            title: '属性名称',
            dataIndex: 'name',
            key: 'name',
            width: "100px",
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: "100px",
            render: text => text ? propertyTypeList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '值',
            dataIndex: 'defaultValue',
            key: 'defaultValue',
            width: "100px",
        },
        {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            width: "80px",
            render: text => text ? unitList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '部位',
            dataIndex: 'definitionPartName',
            key: 'definitionPartName',
            width: "100px",
        },
        {
            title: '是否可见',
            dataIndex: 'isShow',
            key: 'isShow',
            width: "50px",
            render: text => text ? isShowList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '是否生效',
            dataIndex: 'isEffective',
            key: 'isEffective',
            width: "50px",
            render: text => text ? isEffectiveList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '自定义属性',
            dataIndex: 'propertyId',
            key: 'propertyId',
            width: "100px",
            render: text => text && propsList ? propsList.find(item => item.id == text).name.replace(/^([^\,]*).*$/, function ($all, $1) { return $1 }) : ''
        }]
        const columns = mode != 'overview' ? [
            ...c1,
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: "100px",
                render: (text, record) => <span className="operate"> <a onClick={(e) => this.editProp(e, record, 1)}><Icon type="edit" /><span>修改参数</span></a></span>
            }
        ] : [...c1];
        const c2 = [{
            title: 'KEY',
            dataIndex: 'key',
            key: 'key',
            width: "100px",
        },
        {
            title: '属性名称',
            dataIndex: 'name',
            key: 'name',
            width: "100px",
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
            width: "100px",
            render: text => text ? propertyTypeList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '值',
            dataIndex: 'defaultValue',
            key: 'defaultValue',
            width: "100px",
        },
        {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            width: "80px",
            render: text => text ? unitList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '部位',
            dataIndex: 'definitionPartName',
            key: 'definitionPartName',
            width: "100px",
        },
        {
            title: '是否可见',
            dataIndex: 'isShow',
            key: 'isShow',
            width: "50px",
            render: text => text ? isShowList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '是否生效',
            dataIndex: 'isEffective',
            key: 'isEffective',
            width: "50px",
            render: text => text ? isEffectiveList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '自定义属性',
            dataIndex: 'propertyId',
            key: 'propertyId',
            width: "100px",
            render: text => text && propsList ? propsList.find(item => item.id == text).name.replace(/^([^\,]*).*$/, function ($all, $1) { return $1 }) : ''
        }]
        const columns2 = mode != 'overview' ? [
            ...c2,
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: "100px",
                render: (text, record) => <span className="operate"><a onClick={(e) => this.editProp(e, record, 2)}><Icon type="edit" /><span>修改参数</span></a></span>
            }
        ] : [...c2]
        return (
            <div style={loading?{opacity:0}:{opacity:1}}  className="structureDetail">
                <div className="btitle absMiddle"><div><div><div></div>{mode == 'add' ? '新增构件' : '编辑构件'}</div><div><Button onClick={e => {
                    e.preventDefault()
                    this.props.history.go(-1)
                }}>返回</Button></div></div></div>
                <div>
                    <div className="title">基础信息</div>
                    <StructureBase onLoaded={(context) => {
                        this.setState({ context });
                    }} getFormData={this.getFormData} mode={mode} >  <div className={showBg ? 'bgTrans' : 'none'}></div></StructureBase>
                    <div className="title">属性信息</div>
                    <div className="tableBox">
                        <div className="title">customProps</div>
                        <Table loading={tloading} rowKey={record => record.key} bordered pagination={false} dataSource={customProperties ? customProperties : []} columns={columns2} />
                        <div className="title">attributes</div>
                        <Table loading={tloading} rowKey={record => record.key} bordered pagination={false} dataSource={attributeProperties ? attributeProperties : []} columns={columns} />
                    </div>
                </div>
                {
                    mode != 'overview' ? <div className="strBtnBox">
                        <Button onClick={this.submit} loading={loading} disabled={loading}>提交</Button><Button onClick={e => {
                            e.preventDefault()
                            this.props.history.go(-1)
                        }}>返回</Button>
                    </div> : undefined
                }
                <ToolConfigModals
                    onLoaded={context => {
                        this.setState({ modalContext: context })
                    }}
                    parent={this}
                />

            </div>
        )
    }
}
export default connect(
    ({
        dict: { dictlist }
    }) => ({
        dictlist
    })
    , dispatch => ({
        getStructureTree: (values) => dispatch({
            type: 'structure/getCateTree',
            payload: values
        }),
        addDefinition: (values, onSuccess, onError) => dispatch({
            type: 'structure/addDefinition',
            payload: {
                values,
                onSuccess,
                onError,

            }
        }),
        updateDefinition: (values, onSuccess, onError) => dispatch({
            type: 'structure/updateDefinition',
            payload: {
                values,
                onSuccess,
                onError,

            }
        }),
        getDefinitionPropertyByDefinitionId: (values,) => dispatch({
            type: 'structure/getDefinitionPropertyByDefinitionId',
            payload: values
        }),
        cusPropsList: (values) => dispatch({
            type: 'cusProps/cusPropsList',
            payload: values
        }),
    }))(structureDetail);